<template>
  <div class="qycpym">
 
    <div class="header_sele">
      <span>注：寄售设置 是将导入的超市数据置为 '寄售_导入'标记 ，用于寄售在佰联平台</span>
      <div class="sele">
        <span>客户：</span>
        <a-input placeholder="请输入客户名称" style="width: 200px" @change="onSearch" />
        <a-icon type="search" class="search" />
      </div>
    </div>
    <div class="qykc appstyle">
      <div class="add_qy">
        
        <div class="add_in">
          <a
            class="drmbxz"
            style="margin-left: 26px;"
            href="https://vip.bearing.cn/excelfile/template.xls"
          >
            <i>导入模板下载</i>
          </a>
        </div>
        <div class="add_in">
          客户名称：
          <a-select
            showSearch
            :value="khvalue"
            placeholder="客户名称"
            style="width: 200px"
            :defaultActiveFirstOption="false"
            :showArrow="false"
            :filterOption="false"
            @search="khmcSearch"
            @change="khmcChange"
            :notFoundContent="null"
          >
            <a-select-option
              v-for="(item,i) in dataSource"
              :key="i"
              :value="item.GSMC"
            >{{item.GSMC}}</a-select-option>
          </a-select>

        </div>
        <div class="add_in">
          <span>库存上传：</span>
          <div class="scexel">
            <!-- <a-upload-dragger
              name="file"
              accept=".xls, .xlsx"
              @change="Changesjdr"
              :fileList="fileList"
              :showUploadList="true"
              action="https://www.bearing.cn"
              :disabled="drload"
            >
              <p class="ant-upload-drag-icon">
                <a-icon type="upload" />
              </p>
              <p class="ant-upload-text"></p>
            </a-upload-dragger> -->



              <a-upload
                action="https://vip.bearing.cn"
                listType="picture-card"
                :fileList="fileList"
                @preview="handlePreview"
                @change="Changecpimg"
           
              >
               
              
                  <div class="uptext ant-upload-text">
                    <a-icon :type="loadingkc ? 'loading' : 'cloud-upload'" />上传文件
                  </div>
                

              </a-upload>
              <span>{{previewImage}}</span>


            <a-modal v-if="sjdrmodal" title="上传成功" v-model="sjdrmodal" @ok="handleOk">
              <p>数据已载入成功,确认导入吗?</p>
            </a-modal>
          </div>
        </div>

        <div class="add_in">
          <a-button type="primary" @click="scsjexl">确认导入</a-button>
          <div class="load" v-if="drload">
            <a-spin>
              <a-icon slot="indicator" type="loading" style="font-size: 24px" spin />
            </a-spin>
          </div>

         
        </div>
      </div>
      <a-table
        :pagination="pagination"
        :dataSource="data"
        :loading="loading"
        :columns="columns"
        bordered
      >
        <template v-for="titletext in []" :slot="titletext" slot-scope="text, record, index">
          <div :key="titletext"></div>
        </template>

        <template slot="operation" slot-scope="text, record, index">
          <div class="editable-row-operations">
            <span class="del">
              <!-- 客户单个---库存导入 -->
              <a-upload
                name="file"
                accept=".xls, .xlsx"
                :multiple="true"
                action="https://www.bearing.cn"
                :headers="headers"
                @change="Changecpimg"
              >
                <a-button @click="()=>kcdrck(record)">库存导入</a-button>
              </a-upload>
            </span>

            <span class="del" @click="()=>qykcdc(record)">库存导出</span>
            <a-popconfirm class="del" title="确定删除吗?" @confirm="() => kcdelete(record,record.key)">
              <a href="javascript:;">删除</a>
            </a-popconfirm>
            <span class="del" @click="()=>qyreload(record)">刷新</span>
             <!-- <span class="del" @click="()=>setConsign(record)">置为寄售</span> -->
            <span class="del" @click="()=>ckkc(record,record.key)">查看库存</span>
          </div>
        </template>
      </a-table>
    </div>
    <a-modal v-if="kcdrmodal" title="上传成功" v-model="kcdrmodal" @ok="kcdrOk">
      <p>数据已载入成功,确认导入吗?</p>
    </a-modal>
  </div>
</template>

<script>
import qs from "qs";
import moment from "moment";
const columns = [
  {
    title: "客户ID",
    dataIndex: "bearingid"
  },
  {
    title: "客户名称",
    dataIndex: "gysmc"
  },
  {
    title: "已导入数量",
    dataIndex: "total",
    scopedSlots: { customRender: "total" }
  },
   {
    title: "类型",
    dataIndex: "ly",
    scopedSlots: { customRender: "ly" }
  },
  {
    title: "导入时间",
    dataIndex: "gxsj",
    scopedSlots: { customRender: "gxsj" }
  },
  {
    title: "操作",
    dataIndex: "operation",
    scopedSlots: { customRender: "operation" }
  }
];
//上传
// function getBase64(img, callback) {
//   const reader = new FileReader();
//   let file = [];
//   file = reader;
//   reader.addEventListener("load", () => callback(reader.result));
//   reader.readAsDataURL(img);
//   sessionStorage.setItem("file", reader);
// }
const data = [];
export default {
  data() {
    this.cacheData = data.map(item => ({ ...item }));
    return {
      data,
      columns,
      sele: "",
      serchvalue: "",
      pagination: {
        defaultPageSize: 10,
        showTotal: total => `共 ${total} 条数据`,
        total: 0
      },
      loading: true,
      loadingkc:false,
      drload: false,
      datakh: [],
      dataSource: [],
      datakhId: "",
      khvalue: "",
      //库存上传-----------------
      fileList: [
        // {
        //   uid: "-1",
        //   name: "类型(.xls/.xlsx)",
        //   status: "done",
        //   url: "javascript:;"
        // }
      ],
      uploading: false,
      exelUrl: "", //exel表格的baes64格式路径
      khexelUrl: "", //exel表格的baes64格式路径
  previewVisible: false,
            previewImage: '',
      exflage: false, //exel表格
      sjdrmodal: false,
      kcdrmodal: false,

      xlshz: "", //上传的exel表格的后缀名
      //库存上传-----------------
      indicator: <a-icon type="loading" style="font-size: 24px" spin />,
      // fyflag: false,
      headers: {
        authorization: "authorization-text"
      }
    };
  },
  filters: {
    formatDate: function(value) {
      return moment(value).format("YYYY-MM-DD");
    }
  },
  methods: {
    //搜索框
    onSearch(e) {
      this.serchvalue = e.target.value;

      console.log('this.serchvalue',this.serchvalue)
      let data1 = [];
      data1 = this.cacheData;
      let data2 = [];
      for (var i = 0; i < data1.length; i++) {
       //  console.log('this.gysmc',data1[i].gysmc)
    
        if (
         data1[i].gysmc.indexOf(this.serchvalue) > -1 ||
          data1[i].bearingid.indexOf(this.serchvalue) > -1  
        ) {
          data2.push(data1[i]);
        }
      }

      this.data = data2;
    },
    //客户名称
    getkhmc(value) {
      this.axios
        .post("yangben/SelectYbGsmc.php", qs.stringify({ gsmc: value }))
        .then(res => {
          if (res.data.code == 303) {
            this.dataSource = res.data.result;
            if (res.data.result.length == 0) {
              this.dataSource = [];
            }
          }
        });
    },

    //客户名称查询
    khmcChange(value) {
      this.khvalue = value;
      for (var i = 0; i < this.dataSource.length; i++) {
        if (this.khvalue == this.dataSource[i].GSMC) {
          this.datakhId = this.dataSource[i].SQDWID;
        }
      }
      if (this.khvalue == "") {
        this.datakhId = "";
      }
    },
    khmcSearch(value) {
      this.getkhmc(value);
    },
    khmc(input, option) {
      return (
        option.componentOptions.children[0].text
          .toUpperCase()
          .indexOf(input.toUpperCase()) >= 0
      );
    },

    //下拉搜索框
    handleChange(value) {
     // console.log(`selected ${value}`);
    },
    handleBlur() {
     // console.log("blur");
    },
    handleFocus() {
    //  console.log("focus");
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },

    //表格
    handleChangelist(pagination, khmc) {
      this.axios
        .post(
          "kucun/GetBusinessKc.php",
          qs.stringify({
            gysmc: khmc,
            page: pagination.current,
            pageSize: pagination.defaultPageSize
          })
        )
        .then(res => {
          if (res.data.code == 303) {
            this.data = res.data.result;
            this.pagination.total = Number(res.data.result.total);
            this.loading = false;
            this.cacheData = this.data.map(item => ({
              ...item
            }));
            for (var i = 0; i < res.data.result.length; i++) {
              this.data[i].key = i;
            }
          } else {
            this.data = [];
          }
        });
    },

    //删除库存列表
    kcdelete(value, key) {
      const dataSource = [...this.data];
      
      this.data = dataSource.filter(item => item.key !== key);
      this.axios
        .post(
          "kucun/DeleteBusinessKc.php",
          qs.stringify({ sqdwid: value.bearingid,ly:value.ly })
        )
        .then(res => {
          if (res.data.code == 303) {
            this.$notification["success"]({
              message: "成功",
              description: res.data.msg
            });
          } else {
            this.$notification["error"]({
              message: "失败",
              description: res.data.msg
            });
          }
        });
    },

    //库存导入
    kcdrck(data) {
      this.datakhId = data.bearingid;
    },
    //数据导入--文件上传
    scsjexl() {
      if (this.datakhId != "" && this.fileList) {
        this.loadingkc = true;
        this.drload = true;


  
        this.exelUrl=this.fileList[0].thumbUrl
          let name = this.fileList[0].name;
      var i = name.indexOf(".");
      var data = name.substring(i + 1, name.length);
      this.xlshz = data;
           

        this.axios
          .post(
            "kucun/PullBusinessKc.php",
            qs.stringify({
              sqdwid: this.datakhId,
              fileBase: this.exelUrl,
              fileSuffix: this.xlshz
            })
          )
          .then(res => {
         
            if (res.data.code == 303) {
              this.loadingkc = false;
              this.drload = false;

              this.$notification["success"]({
                message: "成功",
                description: res.data.msg
              });
              (this.datakhId = ""),
                (this.khvalue = ""),
                (this.exelUrl = ""),
                (this.fileList[0].name = ".xls/.xlsx");
           
            } else {
              this.drload = false;
              this.$notification["error"]({
                message: "失败",
                description: res.data.msg
              });
            }
          });
      } else if (this.datakhId == "") {
        this.$notification["error"]({
          message: "失败",
          description: "客户名称不能为空"
        });

        return;
      } else {
        this.$notification["error"]({
          message: "失败",
          description: "上传文件不能为空"
        });
      }
    },
    // 客户新增---库存导入

    // Changesjdr(info) {
    //   let fileList = [...info.fileList];
    //   const status = info.file.status;

    //   fileList = fileList.slice(-1);
    //   //上传中....
    //   if (status !== "uploading") {
    //   }
    //   //上传后....
    //   if (status === "done") {
    //     getBase64(info.file.originFileObj, xlxurl => {
    //       this.exelUrl = xlxurl;
    //       this.loading = false;
    //       this.file = info.file.originFileObj;
    //     });
    //     this.sjdrmodal = true;
    //   } else if (status === "error") {
    //     this.$message.error(`${info.file.name} 上传失败.`);
    //   }
    //   fileList = fileList.map(file => {
    //     if (file.response) {
    //     }
    //     return file;
    //   });

    //   this.fileList = fileList;
    //   if (this.fileList == "") {
    //     this.exelUrl = "";
    //   }
    //   if (this.fileList != "") {
    //     let name = this.fileList[0].name;
    //     var i = name.indexOf(".");
    //     var data = name.substring(i + 1, name.length);
    //     this.xlshz = data;
    //   }

    // },
 handleCancel() {
            this.previewVisible = false;
        },
        handlePreview(file) {
            this.previewImage = file.url || file.thumbUrl;
            this.previewVisible = true;
        },
        Changecpimg({ fileList }) {
            this.fileList = fileList;
            console.log(this.fileList)
        },
    // 客户新增--库存导入
    handleOk(e) {
      this.scsjexl();
      this.sjdrmodal = false;
    },

    //导出
    qykcdc(data) {
      this.datakhId = data.bearingid;
      this.axios
        .post(
          "kucun/PushBusinessKc.php",
          qs.stringify({ sqdwid: this.datakhId })
        )
        .then(res => {
          if (res.data.code == 303) {
            this.$notification["success"]({
              message: "成功",
              description: res.data.msg
            });
            location.href = res.data.result;
          } else {
            this.$notification["error"]({
              message: "失败",
              description: res.data.msg
            });
          }
        });
    },

    //刷新页面
    qyreload(value) {
     
      value.gxsj = moment(new Date()).format("YYYY-MM-DD");
      this.axios
        .post(
          "kucun/RefreshKcTime.php",
          qs.stringify({ sqdwid: value.bearingid })
        )
        .then(res => {
         
          if (res.data.code == 303) {
            this.$notification["success"]({
              message: "更新成功",
              description: res.data.msg,
              duration: 1.5
            });
          } else {
            this.$notification["error"]({
              message: "更新失败",
              description: res.data.msg,
              duration: 1.5
            });
          }
        });
    },

     //置为寄售
    setConsign(value) {
     

      this.axios
        .post(
          "kucun/setConsign.php",
          qs.stringify({ sqdwid: value.bearingid })
        )
        .then(res => {
         
          if (res.data.code == 303) {
            value.ly='寄售_导入' 
            this.$notification["success"]({
              message: "设置成功",
              description: res.data.msg,
              duration: 1.5
            });
          } else {
            this.$notification["error"]({
              message: "更新失败",
              description: res.data.msg,
              duration: 1.5
            });
          }
        });
    },

    //查看库存
    ckkc(value, key) {
     
      this.$store.state.qycpymID = value.bearingid;
      this.$store.state.gysmc = value.gysmc;
      this.$router.push("/kcgl");
    }
  },
  computed: {
    filter() {
      return this.data.filter(
        value => !this.serchvalue || value.gysmc.indexOf(this.serchvalue) > -1
      );
   
    }
  },
  created() {
    this.handleChangelist(this.pagination);
    this.getkhmc();
  }
};
</script>

<style lang='less'>
   .ico {
            .anticon-cloud-upload {
                vertical-align: top;
                margin-right  : 5px;
                color         : #40a9ff;
            }

            .uptext {
                font-size  : 20px;
                font-weight: bold;
                color      : #40a9ff;
            }
        }
.qycpym {
  .header_sele {
    position: absolute;
    top: 55px;
    left: 1%;
    z-index: 999;
    text-align: right !important;
    width: 98% !important;
    background-color: #fff;
    box-shadow: 5px 5px 5px #ccc;
    // height: 50px;
    padding: 10px 20px;
    margin: 10px 0!important;
    .sele {
      position: relative;
      display: inline-block;
      i {
        position: absolute;
        top: 10px;
        right: 8px;
      }
    }
  }
  .qykc {
    width: 80%;
    position: relative;
    top: 128px;
    // left: 250px;

    .ant-table-thead {
      background-color: #ccc !important;
    }
    .ant-table-tbody {
      background: #fff !important;
    }
  }

  .add_qy {
    width: 100%;
    text-align: right;
    height: 55px;
    background-color: #fff;
    margin: 0px 0 11px 0;
    .ant-input {
      display: inline-block !important;
      width: 200px;
      height: 30px !important;
      font-size: 14px;
    }
    .add_in {
      position: relative;
      display: inline-block;
      text-align: left;
      margin: 0 10px;
      .load {
        position: absolute;
        background: rgba(255, 255, 255, 0.5);
        top: 0;
        right: 0;
        width: 100%;
        height: 50px;
        .ant-spin-spinning {
          position: relative;
          top: 8px;
          left: 35px;
        }
      }
      .drmbxz {
        color: #000;
        text-decoration: underline;
      }
      .ant-btn {
        height: 40px;
        padding: 0 20px;
      }
      .ant-upload-list {
        position: absolute;
        top: 0;
        left: 28px;
        .ant-upload-list-item {
          width: 130px !important;
        }
      }
      .scexel {
        position: relative;
        top: 13px;
        left: 14px;
        width: 157px !important;
        height: 36px;
        display: inline-block;
        border: 0 !important;
        // box-shadow: -3px 1px 6px #ccc;
        .ant-upload.ant-upload-drag {
          border: 0 !important;
          background-color: #fff;
          width: 20% !important;
          font-size: 25px !important;
        }
        .ant-upload {
          padding: 0px 0 !important;
          height: 20px;
        }
        .ant-upload-drag-icon {
          margin: 0 !important;
          display: inline-block !important;
          .anticon-upload {
            font-size: 25px !important;
            vertical-align: middle !important;
            margin-right: 10px;
            color: #999 !important;
          }
        }
        .ant-upload-text {
          display: inline-block !important;
        }
        .dr {
          position: absolute;
          top: 0;
          right: -92px;
          height: 51px;
        }
        .ant-upload.ant-upload-drag .ant-upload {
          padding: 0px 0 !important;
        }
      }
    }
  }
  .ant-table-wrapper {
    background: #fff !important;
  }
  .fyloading {
    position: absolute;
    width: 90% !important;
    border: 1px solid #91d5ff;
    // background: rgba(255, 255, 255, 0.5);
    padding: 30px;
    height: 800px !important;
    z-index: 999999 !important;
    top: 108px;
    left: 201px;
    // opacity: .5!important;
    .ant-spin-blur {
      opacity: 1 !important;
    }
    .ant-spin-text {
      font-size: 18px !important;
    }
    
  }
  .ant-spin-nested-loading > div > .ant-spin {
    top: 100px !important;
  }
  .del {
    padding-right: 15px;
    color: #40a9ff;
    cursor: pointer;
    .ant-upload-list {
      display: none !important;
    }
    .ant-btn {
      background: transparent !important ;
      border: 0 !important;
      color: #40a9ff !important;
    }
  }
}
</style>
